package org.msd.service;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class Filtermodel implements Filter {//过滤器
    private String encoding = "UTF-8";
    protected FilterConfig filterConfig;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;

        String defaultEncoding = filterConfig.getInitParameter("defaultEncoding");

        // 本过滤器默认编码是UTF-8，但也可以在web.xml配置文件里设置自己需要的编码
        if (defaultEncoding != null) {
            encoding = filterConfig.getInitParameter("defaultEncoding");
        }
    }

    @Override
    public void doFilter(ServletRequest srequset, ServletResponse sresponse, FilterChain filterChain)
            throws IOException, ServletException {

        // 强制转换为Http方式的
        HttpServletRequest request = (HttpServletRequest) srequset;
        HttpServletResponse response = (HttpServletResponse) sresponse;

        // 设置 request和response的编码
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);
        filterChain.doFilter(request, sresponse);
    }

    public void destroy() {
        this.encoding = null;
    }
}